package entity

import (
	"time"
	"xr-game-server/core/constants/db"
	"xr-game-server/core/migrate"
	"xr-game-server/core/snowflake"
	"xr-game-server/core/syndb"
)

const (
	TbGuildBlackList db.TbName = "guild_black_lists"
)

const (
	GuildBlackListGuildId   db.TbCol = "guild_id"
	GuildBlackListRoleId    db.TbCol = "role_id"
	GuildBlackListBlackTime db.TbCol = "black_time"
)

type GuildBlackList struct {
	migrate.MoreModel
	GuildId   uint64     `gorm:"comment:公会ID"`
	RoleId    uint64     `gorm:"comment:拉黑角色ID"`
	BlackTime *time.Time `gorm:"default:null;comment:拉黑时间"`
}

func (ga *GuildBlackList) SetBlackTime(target *time.Time) {
	ga.BlackTime = target
	ga.SetUpdatedAt(time.Now())
	syndb.AddDataToLazyChan(TbGuildBlackList, GuildBlackListBlackTime, &syndb.ColData{
		IdVal:  ga.ID,
		ColVal: target,
	})
}
func (ga *GuildBlackList) SetGuildId(guildId uint64) {
	ga.GuildId = guildId
	ga.SetUpdatedAt(time.Now())
	syndb.AddDataToLazyChan(TbGuildBlackList, GuildBlackListGuildId, &syndb.ColData{
		IdVal:  ga.ID,
		ColVal: guildId,
	})
}
func (ga *GuildBlackList) SetRoleId(roleId uint64) {
	ga.RoleId = roleId
	ga.SetUpdatedAt(time.Now())
	syndb.AddDataToLazyChan(TbGuildBlackList, GuildBlackListRoleId, &syndb.ColData{
		IdVal:  ga.ID,
		ColVal: roleId,
	})
}
func (ga *GuildBlackList) SetCreatedAt(time time.Time) {
	ga.CreatedAt = time
	syndb.AddDataToLazyChan(TbGuildBlackList, db.CreatedAtName, &syndb.ColData{
		IdVal:  ga.ID,
		ColVal: time,
	})
}
func (ga *GuildBlackList) SetUpdatedAt(time time.Time) {
	ga.UpdatedAt = time
	syndb.AddDataToLazyChan(TbGuildBlackList, db.UpdatedAtName, &syndb.ColData{
		IdVal:  ga.ID,
		ColVal: time,
	})
}
func (ga *GuildBlackList) SetDeletedAt(time time.Time) {
	ga.DeletedAt = time
	syndb.AddDataToLazyChan(TbGuildBlackList, db.DeletedAtName, &syndb.ColData{
		IdVal:  ga.ID,
		ColVal: time,
	})
}
func (ga *GuildBlackList) SetIsDeleted(deleted bool) {
	ga.IsDeleted = deleted
	ga.SetUpdatedAt(time.Now())
	syndb.AddDataToLazyChan(TbGuildBlackList, db.IsDeletedName, &syndb.ColData{
		IdVal:  ga.ID,
		ColVal: deleted,
	})
}

func (ga *GuildBlackList) IsBlackList() bool {
	return ga.BlackTime != nil && !ga.IsDeleted && ga.BlackTime.After(time.Now())
}

func initGuildBlackList() {

	syndb.RegLazyWithMiddle(TbGuildBlackList, db.IsDeletedName)
	syndb.RegLazyWithMiddle(TbGuildBlackList, db.DeletedAtName)
	syndb.RegLazyWithMiddle(TbGuildBlackList, db.CreatedAtName)
	syndb.RegLazyWithMiddle(TbGuildBlackList, db.UpdatedAtName)

	syndb.RegLazyWithMiddle(TbGuildBlackList, GuildBlackListGuildId)
	syndb.RegLazyWithMiddle(TbGuildBlackList, GuildBlackListRoleId)
	syndb.RegLazyWithMiddle(TbGuildBlackList, GuildBlackListBlackTime)

	migrate.AutoMigrate(&GuildBlackList{})
}

func NewGuildBlackList(guildId uint64, roleId uint64) *GuildBlackList {
	ret := &GuildBlackList{}
	ret.ID = snowflake.GetId()
	ret.SetGuildId(guildId)
	ret.SetRoleId(roleId)
	ret.SetIsDeleted(true)
	ret.SetCreatedAt(time.Now())
	ret.SetUpdatedAt(time.Now())
	return ret
}
